package com.yaowk.system.controller;

import com.feizhou.swagger.annotation.Api;
import com.feizhou.swagger.annotation.ApiOperation;
import com.feizhou.swagger.annotation.Param;
import com.feizhou.swagger.annotation.Params;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.yaowk.common.controller.BaseController;
import com.yaowk.system.model.Platform;
import com.yaowk.system.model.User;
import com.yaowk.system.model.UserPlatform;
import com.yaowk.system.shiro.TokenKit;
import com.yaowk.system.validator.PlatformIdValidator;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.*;

/**
 * @authc yaowk
 * 2017/7/16
 */
@RequiresAuthentication
@RequiresPermissions("system:platform")
@Before(PlatformIdValidator.class)
@Api(url = "/system/platform", description = "平台管理,需权限system:platform", tag = "Platform")
public class PlatformController extends BaseController {

    @ApiOperation(url = "/", description = "查看平台信息详情")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true, dataType = "Integer")
    })
    public void index() {
        Integer id = getParaToInt("platformId");
        Platform platform = Platform.dao.findById(id);
        renderJson(platform);
    }

    @Clear(PlatformIdValidator.class)
    @ApiOperation(url = "/list", description = "查看登录用户平台列表")
    @Params({
            @Param(name = "pageNumber", description = "当前页", dataType = "Integer"),
            @Param(name = "pageSize", description = "页面大小", dataType = "Integer")
    })
    public void list() {
        Kv condition = Kv.by("userId = ", TokenKit.getUserId());
        Page<UserPlatform> page = UserPlatform.dao.paginate(getPage(), condition);
        List<Platform> platforms = new ArrayList<>();
        for (UserPlatform userPlatform : page.getList()) {
            Platform platform = Platform.dao.findById(userPlatform.getPlatformId());
            platforms.add(platform);
        }
        Page<Platform> platformPage = new Page<>(platforms, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
        renderJson(platformPage);
    }

    @Clear(PlatformIdValidator.class)
    @RequiresPermissions("system:platform:allList")
    @ApiOperation(url = "/allList", description = "查看所有平台列表，需权限system:platform:allList")
    @Params({
            @Param(name = "pageNumber", description = "当前页", dataType = "Integer"),
            @Param(name = "pageSize", description = "页面大小", dataType = "Integer")
    })
    public void allList() {
        Kv condition = Kv.by("status != ", Platform.STATUS_DELETE);
        Page<Platform> page = Platform.dao.paginate(getPage(), condition);
        renderJson(page);
    }

    @ApiOperation(url = "/userList", description = "查看登录用户相对于该平台的子用户列表情况")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true, dataType = "Integer"),
            @Param(name = "pageNumber", description = "当前页", dataType = "Integer"),
            @Param(name = "pageSize", description = "页面大小", dataType = "Integer")
    })
    public void userList() {
        Page<User> page = User.dao.paginate(getPage(), Kv.by("parentId = ", TokenKit.getUserId()));
        List<UserPlatform> userPlatformList = UserPlatform.dao.find(Kv.by("platformId = ", getParaToInt("platformId")));
        Set<Integer> userIdSet = new HashSet<>();
        for (UserPlatform userPlatform : userPlatformList) {
            userIdSet.add(userPlatform.getUserId());
        }
        for (User user : page.getList()) {
            if (userIdSet.contains(user.getId())) {
                user.put("checked", true);
            } else {
                user.put("checked", false);
            }
        }
        renderJson(page);
    }

    @Before(Tx.class)
    @Clear(PlatformIdValidator.class)
    @RequiresPermissions("system:platform:add")
    @ApiOperation(url = "/add", description = "添加平台，需权限system:platform:add", httpMethod = "post")
    @Params({
            @Param(name = "name", description = "平台名称", required = true),
            @Param(name = "logo", description = "logo")
    })
    public void add() {
        Platform platform = getBean(Platform.class, "", true);
        platform.save();
        new UserPlatform().setUserId(TokenKit.getUserId()).setPlatformId(platform.getId()).save();
        renderJson(platform);
    }

    @Before(Tx.class)
    @RequiresPermissions("system:platform:edit")
    @ApiOperation(url = "/edit", description = "修改平台，需权限system:platform:edit", httpMethod = "post")
    @Params({
            @Param(name = "name", description = "平台名称", required = true),
            @Param(name = "logo", description = "logo"),
            @Param(name = "platformId", description = "平台Id", required = true)
    })
    public void edit() {
        Platform platform = getBean(Platform.class, "", true);
        platform.setId(getParaToInt("platformId"));
        platform.update();
        renderJson(platform);
    }

    @Before(Tx.class)
    @RequiresPermissions("system:platform:delete")
    @ApiOperation(url = "/delete", description = "删除平台，需权限system:platform:delete")
    @Params({
            @Param(name = "platformId", description = "平台Id", required = true)
    })
    public void delete() {
        Integer platformId = getParaToInt("platformId");
        new Platform().setId(platformId).delete();
        renderSuccess();
    }

    @RequiresPermissions("system:platform:userEdit")
    @ApiOperation(url = "/userEdit", description = "修改平台和用户关系，需权限system:platform:userEdit", httpMethod = "post")
    @Params({
            @Param(name = "platformId", description = "平台Id", required = true),
            @Param(name = "userId", description = "用户id", dataType = "Integer[]")
    })
    public void userEdit() {
        Integer platformId = getParaToInt("platformId");
        Integer[] userIds = getParaValuesToInt("userId");
        if (ArrayUtil.isNotEmpty(userIds)) {
            // 先查询这个管理员的下属
            Kv condition = Kv.by("parentId = ", TokenKit.getUserId());
            List<User> users = User.dao.find(condition);
            List<Integer> list = Arrays.asList(userIds);
            // 如果下属不在选中，移除下属和下属的下属...
            for (User user : users) {
                if (!list.contains(user.getId())) {
                    condition = Kv.by("userId = ", user.getId()).set("platformId = ", platformId);
                    List<UserPlatform> userPlatforms = UserPlatform.dao.find(condition);
                    for (UserPlatform userPlatform : userPlatforms) {
                        deleteByUserParentId(userPlatform);
                    }
                }
            }

            // 查询该平台的所有操作者
            condition = Kv.by("platformId = ", platformId);
            List<UserPlatform> userPlatforms = UserPlatform.dao.find(condition);
            list = new ArrayList<>();
            for (UserPlatform userPlatform : userPlatforms) {
                list.add(userPlatform.getUserId());
            }
            // 如果选中不在操作者中，加入
            for (Integer userId : userIds) {
                if (!list.contains(userId)) {
                    new UserPlatform().setUserId(userId).setPlatformId(platformId).save();
                }
            }
        } else {
            // 下属以下全部清除
            // 先查询这个管理员的下属
            Kv condition = Kv.by("parentId = ", TokenKit.getUserId());
            List<User> users = User.dao.find(condition);
            for (User user : users) {
                condition = Kv.by("userId = ", user.getId()).set("platformId = ", platformId);
                List<UserPlatform> userPlatforms = UserPlatform.dao.find(condition);
                for (UserPlatform userPlatform : userPlatforms) {
                    deleteByUserParentId(userPlatform);
                }
            }
        }

        renderSuccess();
    }

    private void deleteByUserParentId(UserPlatform userPlatform) {
        userPlatform.delete();
        Kv condition = Kv.by("parentId = ", userPlatform.getUserId());
        List<User> users = User.dao.find(condition);
        if (users.size() == 0) {
            return;
        }
        for (User user : users) {
            condition = Kv.by("userId = ", user.getId()).set(" platformId = ", userPlatform.getPlatformId());
            List<UserPlatform> userPlatforms = UserPlatform.dao.find(condition);
            for (UserPlatform userPlatform1 : userPlatforms) {
                deleteByUserParentId(userPlatform1);
            }
        }
    }
}
